package cc.angis.xiugallery.db;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import cc.angis.xiugallery.data.FolderData;

public class FavouriteDBHelper extends BaseDBHelper {
	
	public FavouriteDBHelper(){
		
	}
	
	public FavouriteDBHelper(Context context, String table){
		super(context, table);
	}
	
	public FavouriteDBHelper(Context context, String table, ContentValues values){
		super(context, table, values);
	}
	
	public long delete(int id){
		mWhereClaus = "id=?";
		mWhereArgs = new String[] { String.valueOf(id) };
		return delDB();
	}
	
	public long update(int id, String name, long lastImgId, int count){
		mWhereClaus = "id=?";
		mWhereArgs = new String[] { String.valueOf(id) };
		mValues = new ContentValues();
		if (name != null)
			mValues.put(TableConstants.FavouriteColumn.NAME, name);
		if (lastImgId != -1)
			mValues.put(TableConstants.FavouriteColumn.LASTIMAGEID, lastImgId);
		if(count > 0)
			mValues.put(TableConstants.FavouriteColumn.IMGCOUNT, count);
		mValues.put(TableConstants.FavouriteColumn.LASTUPDATE, Calendar.getInstance().getTimeInMillis());
		return updateDB();
	}
	
	public long insert(String name){
		mValues = new ContentValues();
		mValues.put(TableConstants.FavouriteColumn.NAME, name);
		mValues.put(TableConstants.FavouriteColumn.LASTUPDATE, Calendar.getInstance().getTimeInMillis());
		mValues.put(TableConstants.FavouriteColumn.LASTIMAGEID, -2);
		mValues.put(TableConstants.FavouriteColumn.IMGCOUNT, 0);
		return insertDB();
	}
	
	public List<FolderData> getAllFavs(){
		List<FolderData> favs = new ArrayList<FolderData>();
		Cursor cursor = mDBHelper.getReadableDatabase().query(mTable, null, null, null, null, null, TableConstants.FavouriteColumn.LASTUPDATE + " DESC");
		int favIdColumn = cursor.getColumnIndex(
				TableConstants.FavouriteColumn.ID);
		int favNameColumn = cursor.getColumnIndex(
				TableConstants.FavouriteColumn.NAME);
		int lastImgColumn = cursor.getColumnIndex(
				TableConstants.FavouriteColumn.LASTIMAGEID);
		int imgCountColumn = cursor.getColumnIndex(
				TableConstants.FavouriteColumn.IMGCOUNT);
		if (cursor.moveToFirst()){
			FolderData folderData;
			do {
				folderData = new FolderData(String.valueOf(cursor.getInt(favIdColumn)), cursor.getString(favNameColumn), cursor.getInt(imgCountColumn));
				Long lastImgId = cursor.getLong(lastImgColumn);
				if (lastImgId != null && lastImgId.longValue() != -1)
				{
					folderData.addThumbnail(lastImgId);
				}
				favs.add(folderData);
			}while(cursor.moveToNext());
		}
		cursor.close();
		return favs;
	}
	
}
